package com.bangdream.michelia.view.activity.curriculum;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bangdream.michelia.R;
import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.contract.CollectionContract;
import com.bangdream.michelia.contract.CoursesContract;
import com.bangdream.michelia.contract.TeacherContract;
import com.bangdream.michelia.entity.BaseEntity;
import com.bangdream.michelia.entity.CollectionBean;
import com.bangdream.michelia.entity.CollectionRecordBean;
import com.bangdream.michelia.entity.RxEventBean;
import com.bangdream.michelia.entity.TeacherBean;
import com.bangdream.michelia.entity.UserBean;
import com.bangdream.michelia.entity.VideoRxBean;
import com.bangdream.michelia.entity.courses.CourseInfoBean;
import com.bangdream.michelia.entity.courses.TeacherListBean;
import com.bangdream.michelia.entity.courses.VideoMsgBean;
import com.bangdream.michelia.presenter.CollectionPresenter;
import com.bangdream.michelia.presenter.CoursesPresenter;
import com.bangdream.michelia.presenter.TeacherPresenter;
import com.bangdream.michelia.tool.LandLayoutVideo;
import com.bangdream.michelia.tool.retrofithttp.RetroFactory;
import com.bangdream.michelia.utils.ImageLoadUtils;
import com.bangdream.michelia.utils.L;
import com.bangdream.michelia.utils.PublicUtil;
import com.bangdream.michelia.utils.RxBus;
import com.bangdream.michelia.utils.TextViewUtil;
import com.bangdream.michelia.utils.ToastUtil;
import com.bangdream.michelia.view.activity.base.SwipeBackActivity;
import com.bangdream.michelia.view.activity.buy.BuyInfo;
import com.bangdream.michelia.view.activity.currency.MainActivity;
import com.bangdream.michelia.view.custom.ratingstar.RatingStarView;
import com.bangdream.michelia.view.fragment.main.curriculum.CurriculumDetailsChapter;
import com.bangdream.michelia.view.fragment.main.curriculum.CurriculumDetailsData;
import com.bangdream.michelia.view.fragment.main.curriculum.CurriculumDetailsEvaluate;
import com.bangdream.michelia.view.fragment.main.curriculum.CurriculumDetailsIntroduce;
import com.bangdream.michelia.view.fragment.main.curriculum.CurriculumDetailsLecturer;
import com.google.gson.Gson;
import com.google.gson.annotations.JsonAdapter;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.builder.GSYVideoOptionBuilder;
import com.shuyu.gsyvideoplayer.listener.GSYSampleCallBack;
import com.shuyu.gsyvideoplayer.listener.GSYVideoProgressListener;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;

import org.json.JSONArray;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sharesdk.onekeyshare.OnekeyShare;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;

/**
 * @date on 2018/7/23 13:45
 * @email 909732184@qq.com
 * 课程详情
 */
public class CurriculumDetails extends SwipeBackActivity<CoursesContract.ICoursesInfo, CoursesPresenter<CoursesContract.ICoursesInfo>>
        implements View.OnClickListener, ViewPager.OnPageChangeListener, CoursesContract.ICoursesInfo, CollectionContract.ICollectionView, TeacherContract.ITeacherView {
    private RelativeLayout titleBar;
    private ImageView head_img_right, head_img_right2;
    private ViewPager viewPager;
    private TextView[] btnTvs = new TextView[5];
    private FragmentPagerAdapter fragmentPagerAdapter;
    //选项卡被选中和未选中时的字体颜色
    private int onTextColor, offTextColor;
    //viewpage的线条指示器
    private RelativeLayout indicatorView;
    //记录移动的开始位置 初始0
    private int previousPosition = 0;
    //屏幕的宽度
    private int screenWidth;
    //为了实现评论框出现在输入法上面的效果 真正实现评论功能的输入框在activity中fragment中的评论输入框只用于占位
    private LinearLayout evaluateTextLayout;
    private String courseId;
    private String teacherId,title;
    //    private CoursesBean data;
    private TextView tvVideoTime, tvCourseTime, tvTerm, tvViewCount, tvTeacherName, tvMoneyNumber, tvNumber;
    private TextView btnComment;
    private RelativeLayout purchaseLayout;
    private CurriculumDetailsIntroduce item1;
    private CurriculumDetailsLecturer item2;
    private CurriculumDetailsChapter item3;
    private CurriculumDetailsEvaluate item4;
    private CurriculumDetailsData item5;
    private RatingStarView starView;
    private TextView btnBuy;
    private CollectionPresenter collectionParameters;
    TeacherPresenter teacherPresenter;
    private UserBean userBean;
    //收藏记录的id  收藏成功后返回 用于取消收藏
    private String stCollectionRecordId;
    private LandLayoutVideo video_player;
    private OrientationUtils orientationUtils;
    private GSYVideoOptionBuilder gsyVideoOption;
    private GSYVideoOptionBuilder builder;
    private Disposable disposable;
    private int videoPosition;
    CourseInfoBean data;
    double price = 0.0;
    double learnHour = 0;
    long cruLearnHour = 0;
    VideoRxBean videoRxBean;
    boolean isFirst = true;
    private boolean isPlay;
    private boolean isPause;

    @Override
    public int getLayout() {
        return R.layout.activity_curriculum_details;
    }

    @Override
    public void findId() {
        btnComment = findViewById(R.id.btnComment);
        btnBuy = findViewById(R.id.btnBuy);
        purchaseLayout = findViewById(R.id.purchaseLayout);
        tvNumber = findViewById(R.id.tvNumber);
        tvMoneyNumber = findViewById(R.id.tvMoneyNumber);
        starView = findViewById(R.id.starView);
        titleBar = findViewById(R.id.titleBar);
        tvVideoTime = findViewById(R.id.tvVideoTime);
        tvCourseTime = findViewById(R.id.tvCourseTime);
        tvTerm = findViewById(R.id.tvTerm);
        tvViewCount = findViewById(R.id.tvViewCount);
        tvTeacherName = findViewById(R.id.tvTeacherName);
        head_img_right = findViewById(R.id.head_img_right);
        head_img_right2 = findViewById(R.id.head_img_right2);
        viewPager = findViewById(R.id.viewPager);
        video_player = findViewById(R.id.video_player);
        initVideoPlayer();
        onTextColor = ContextCompat.getColor(this, R.color.common_red);
        offTextColor = ContextCompat.getColor(this, R.color.black_text);
        indicatorView = findViewById(R.id.indicatorView);
        btnTvs[0] = findViewById(R.id.btnTv1);
        btnTvs[1] = findViewById(R.id.btnTv2);
        btnTvs[2] = findViewById(R.id.btnTv3);
        btnTvs[3] = findViewById(R.id.btnTv4);
        btnTvs[4] = findViewById(R.id.btnTv5);
        evaluateTextLayout = findViewById(R.id.evaluateTextLayout);
        userBean = AppCurrentUser.getInstance().getUserInfo();
        operateBus();
    }

    private void initVideoPlayer() {

        //外部辅助的旋转，帮助全屏
        orientationUtils = new OrientationUtils(this, video_player);
        //初始化不打开外部的旋转
        orientationUtils.setEnable(false);
        gsyVideoOption = new GSYVideoOptionBuilder();
        video_player.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                orientationUtils.resolveByClick();
                video_player.startWindowFullscreen(CurriculumDetails.this, true, true);
            }
        });

        builder = gsyVideoOption.setIsTouchWiget(true)
                .setRotateViewAuto(false)
                .setLockLand(false)
                .setShowFullAnimation(false)
                .setNeedLockFull(true)
                .setSeekRatio(1f)
                .setCacheWithPlay(false)
                .setVideoAllCallBack(new GSYSampleCallBack() {
                    @Override
                    public void onPrepared(String url, Object... objects) {
                        orientationUtils.setEnable(true);

                        Message message = new Message();
                        message.what = 0x08;
                        handler.sendMessage(message);
                        isPlay=true;
                    }

                    @Override
                    public void onQuitFullscreen(String url, Object... objects) {
                        super.onQuitFullscreen(url, objects);
                        orientationUtils.backToProtVideo();
                    }

                    @Override
                    public void onAutoComplete(String url, Object... objects) {
                        super.onAutoComplete(url, objects);
                        List<Fragment> fragments = getSupportFragmentManager().getFragments();
                        for (int i = 0; i < fragments.size(); i++) {
                            if (fragments.get(i) instanceof CurriculumDetailsChapter) {
                                CurriculumDetailsChapter fragment = (CurriculumDetailsChapter) fragments.get(i);
                                fragment.setLearned(videoPosition);
                                fragment.initVideo(videoPosition + 1);
                                break;
                            }
                        }
//                        CurriculumDetailsChapter fragment = (CurriculumDetailsChapter) getSupportFragmentManager().getFragments().get(2);
                    }


                })
                .setGSYVideoProgressListener(new GSYVideoProgressListener() {
                    @Override
                    public void onProgress(int progress, int secProgress, int currentPosition, int duration) {
                        if (progress >= 99) {
                            cruLearnHour = duration / 1000;
                        } else {
                            cruLearnHour = currentPosition / 1000;
                        }
                    }
                })
        ;

    }

    @Override
    public void onBackPressed() {
        orientationUtils.backToProtVideo();
        if (GSYVideoManager.backFromWindowFull(CurriculumDetails.this)) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        //如果旋转了就全屏
        if (isPlay && !isPause) {
            video_player.onConfigurationChanged(this, newConfig, orientationUtils, true, true);
        }
    }

    @Override
    public void setListener() {
        head_img_right2.setOnClickListener(this);
        head_img_right.setOnClickListener(this);
        btnBuy.setOnClickListener(this);
        btnComment.setOnClickListener(this);
        viewPager.addOnPageChangeListener(this);
        for (TextView textView : btnTvs) {
            textView.setOnClickListener(this);
        }
        starView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tvNumber.setText((int) starView.getRating() + "分");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (collectionParameters != null) {
            collectionParameters.detach();
        }
        if (disposable != null) {
            disposable.dispose();
        }
        if (teacherPresenter != null) {
            teacherPresenter.detach();
        }
        saveWatching();
        GSYVideoManager.releaseAllVideos();
        orientationUtils.releaseListener();
    }



    @Override
    public void logic() {
        if (getIntent().getExtras() != null) {
            courseId = getIntent().getStringExtra("id");
            teacherId = getIntent().getStringExtra("teacherId");
            title = getIntent().getStringExtra("title");
        }
        initTitleBar(" ", title, "", this);
        collectionParameters = new CollectionPresenter();
        collectionParameters.attach(this);
        screenWidth = MainActivity.screenWidth;
//        head_img_right.setImageResource(R.mipmap.kc_share_icon);
        head_img_right.setVisibility(View.VISIBLE);

        head_img_right2.setImageResource(R.mipmap.rw_zan_icon);
        head_img_right2.setVisibility(View.VISIBLE);

        if (courseId != null) {
            Map map = new HashMap();
            map.put("id", courseId);
            mPresenter.getCourseInfo(map, pd);
        }

    }


    @Override
    public CoursesPresenter createPresenter() {
        return new CoursesPresenter<>();
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        //线条指示器移动
        TranslateAnimation ani = new TranslateAnimation(
                previousPosition * screenWidth / 5,
                position * screenWidth / 5, 0, 0);
        ani.setDuration(200);
        ani.setFillAfter(true);
        ani.setInterpolator(new AccelerateDecelerateInterpolator());
        //播放动画
        indicatorView.startAnimation(ani);
        //将这一次的位置保存起来，作为下一次移动的起始位置
        previousPosition = position;


        for (int i = 0; i < btnTvs.length; i++) {
            if (i == position) {
                btnTvs[i].setTextColor(onTextColor);
            } else {
                btnTvs[i].setTextColor(offTextColor);
            }
        }
//        if(position!=3){
//            evaluateTextLayout.setVisibility(View.GONE);
//        }else {
//            if(data!=null && data.isComment()){
//                evaluateTextLayout.setVisibility(View.GONE);
//            }else {
//                evaluateTextLayout.setVisibility(View.VISIBLE);
//            }
//        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }


    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.btnTv1:
                viewPager.setCurrentItem(0);
                break;
            case R.id.btnTv2:
                viewPager.setCurrentItem(1);
                break;
            case R.id.btnTv3:
                viewPager.setCurrentItem(2);
                break;
            case R.id.btnTv4:
                viewPager.setCurrentItem(3);
                break;
            case R.id.btnTv5:
                viewPager.setCurrentItem(4);
                break;
            case R.id.btnBuy:
                if (data != null && data.getId() != null) {
                    Intent intent = new Intent(this, BuyInfo.class);
                    intent.putExtra("id", data.getId());
                    intent.putExtra("price", price);
                    intent.putExtra("title", data.getName());
                    intent.putExtra("title", "3");
                    startActivity(intent);
                }
                break;
            case R.id.btnComment:
                if (item4 == null)
                    return;
                item4.submitComment((int) (starView.getRating()));
                break;
            case R.id.head_img_right2:
                //收藏与取消收藏
                actionCollection();
                break;
//            case R.id.head_img_right:
//                //分享
//                showShare();
//                break;
            default:
                break;
        }
    }


    //收藏与取消收藏
    private void actionCollection() {
        if (stCollectionRecordId == null||stCollectionRecordId.equals("")) {
            if (collectionParameters != null && courseId != null) {
                collectionParameters.actionCollection(courseId, userBean.getId(), pd);
            }
        } else {
            collectionParameters.actionCencelCollection(stCollectionRecordId, pd);
        }
    }

    //改变收藏状态
    private void changeCollectionState(String stRecordId) {
        this.stCollectionRecordId = stRecordId;
        if (stCollectionRecordId == null||stCollectionRecordId.equals("")) {
            head_img_right2.setImageResource(R.mipmap.rw_zan_icon);
        } else {
            head_img_right2.setImageResource(R.mipmap.kc_fav_icon_on);
        }
    }

    //触摸空白处关闭软键盘
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (isHideInput) {
            View view = getCurrentFocus();
            if (isHideInput(view, ev)) {
                HideSoftInput(view.getWindowToken());
            }
        }
        return super.dispatchTouchEvent(ev);
    }


    //填充数据
    private void setViewData(CourseInfoBean bean) {
        if (bean == null)
            return;
        data = bean;

        List<TeacherListBean> teacherListBeans = bean.getTeacherListBeans();
        JSONObject object = (JSONObject) com.alibaba.fastjson.JSONObject.toJSON(bean);
        if (teacherListBeans != null && teacherListBeans.size() > 0) {
            teacherPresenter = new TeacherPresenter();
            teacherPresenter.attach(this);
            teacherPresenter.getTeacherDetails(teacherListBeans.get(0).getTeacherId());

        }

        //设置视频封面
        ImageView imageView = new ImageView(this);
        ImageLoadUtils.ImageLoad(CurriculumDetails.this, bean.getFaceUrl(), imageView, -1);
        video_player.setThumbImageView(imageView);
        builder.build(video_player);
        //通过收藏记录id 改变收藏状态
        changeCollectionState(bean.getCollectId());
//        if (bean.isBuy()) {
//            purchaseLayout.setVisibility(View.GONE);
//        } else {
//            purchaseLayout.setVisibility(View.VISIBLE);
//            video_player.getStartButton().setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                    ToastUtil.showShortToast(CurriculumDetails.this, "您还未购买此课程");
//                }
//            });
//        }
        List<CourseInfoBean.CoursePriceListBean> coursePriceList = bean.getCoursePriceList();

        if (coursePriceList != null && coursePriceList.size() > 0) {
            for (int i = 0; i < coursePriceList.size(); i++) {
                price += coursePriceList.get(i).getPrice();
            }
        }
        tvMoneyNumber.setText("¥" + price + "");
        String stCourseTime = bean.getChapterInfos() == null ? "0节课时" : bean.getChapterInfos().size() + "节课时";

        tvCourseTime.setText(stCourseTime);
        tvViewCount.setText(bean.getLearnCount() + "人");
        tvVideoTime.setText( PublicUtil.tranForm2(bean.getPeriod()) + "小时");
        TextViewUtil.setTextEmpty(tvTerm, bean.getDeadline(), "不限期");
        final Bundle bundle = new Bundle();
        bundle.putParcelable("data", bean);
        fragmentPagerAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
            @Override
            public Fragment getItem(int position) {

                switch (position) {
                    case 0:
                        item1 = new CurriculumDetailsIntroduce();
                        item1.setArguments(bundle);
                        return item1;
                    case 1:
                        item2 = new CurriculumDetailsLecturer();
                        item2.setArguments(bundle);
                        return item2;
                    case 2:
                        item3 = new CurriculumDetailsChapter();
                        item3.setArguments(bundle);
                        return item3;
                    case 3:
                        item4 = new CurriculumDetailsEvaluate();
                        item4.setArguments(bundle);
                        return item4;
                    case 4:
                        item5 = new CurriculumDetailsData();
                        item5.setArguments(bundle);
                        return item5;
                    default:
                        return null;
                }
            }

            @Override
            public int getCount() {
                return btnTvs.length;
            }
        };
        viewPager.setAdapter(fragmentPagerAdapter);
        viewPager.setOffscreenPageLimit(fragmentPagerAdapter.getCount());

    }


    private void showShare() {
        OnekeyShare oks = new OnekeyShare();
        //关闭sso授权
        oks.disableSSOWhenAuthorize();

        // title标题，微信、QQ和QQ空间等平台使用
        oks.setTitle(getString(R.string.app_name));
        // titleUrl QQ和QQ空间跳转链接
        oks.setTitleUrl("http://sharesdk.cn");
        // text是分享文本，所有平台都需要这个字段
        oks.setText("我是分享文本");
        // imagePath是图片的本地路径，Linked-In以外的平台都支持此参数
        //oks.setImagePath("/sdcard/test.jpg");//确保SDcard下面存在此张图片
        // url在微信、微博，Facebook等平台中使用
        oks.setUrl("http://sharesdk.cn");
        // site是分享此内容的网站名称，仅在QQ空间使用
        oks.setSite(getString(R.string.app_name));
        // comment是我对这条分享的评论，仅在人人网使用
        oks.setComment("我是测试评论文本");
        // siteUrl是分享此内容的网站地址，仅在QQ空间使用
        oks.setSiteUrl("http://sharesdk.cn");
        oks.setSilent(true);
        // 启动分享GUI
        oks.show(this);
    }

    @Override
    public void setCollectionList(boolean isSuccess, int page, List<CollectionBean> data, String stDescribe) {

    }

    @Override
    public void actionCollection(boolean isSuccess, CollectionRecordBean data, String stDescribe) {
        if (isSuccess && data != null) {
            changeCollectionState(data.getId());
            showText("收藏成功");
        }
    }

    @Override
    public void actionCencelCollection(boolean isSuccess, String stDescribe) {
        if (isSuccess) {
            changeCollectionState(null);
            showText(stDescribe);
        }
    }

    @Override
    public void setCourseInfo(boolean isSuccess, CourseInfoBean bean) {
        if (isSuccess) {
            setViewData(bean);
        }

    }

    @Override
    public void setVideo(VideoMsgBean url) {

    }


    @SuppressLint("CheckResult")
    public void operateBus() {
        disposable = RxBus.getInstance().toObservable().map(new Function<Object, RxEventBean>() {
            @Override
            public RxEventBean apply(Object o) throws Exception {
                return (RxEventBean) o;
            }
        }).subscribe(new Consumer<RxEventBean>() {
            @Override
            public void accept(RxEventBean eventMsg) throws Exception {
                if (eventMsg != null) {
                    if (eventMsg.getCode() == 0x01) {
                        if (!isFirst) saveWatching();
                        isFirst = false;
                        learnHour = 0;
                        cruLearnHour = 0;
                        videoPosition = eventMsg.getPosition();
                        videoRxBean = (VideoRxBean) eventMsg.getMsg();
                        builder.setUrl(videoRxBean.getUrl()).build(video_player);
                        learnHour = videoRxBean.getLearnHour();
                        video_player.getCurrentPlayer().startPlayLogic();

                    }
                }
            }
        });
    }

    @Override
    public void setTeacherList(boolean isSuccess, int page, List<TeacherBean> data, String stDescribe) {
    }

    @Override
    public void setTeacherDetails(boolean isSuccess, TeacherBean data, String stDescribe) {
        if (isSuccess && data != null) {
            tvTeacherName.setText(data.getName());
            item2.setView(data);
        }else{
            tvTeacherName.setText("暂无");
            item2.setView(null);

        }
    }

    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0x08) {
                long time = Double.valueOf(learnHour).longValue();
                if (time > 0) {
                    GSYVideoManager.instance().getPlayer().seekTo(time * 1000);
                    learnHour=0;

                }
            }
        }
    };

    private void saveWatching() {
        if (videoRxBean != null) {

            Map map = new HashMap();

            map.put("chapterId", videoRxBean.getChapterId());//章节id
            map.put("courseId", data.getId());//课程id
            map.put("id", videoRxBean.getId());//章节学习记录id
            map.put("learnHour", cruLearnHour);//学习时长
            RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"), JSON.toJSONString(map));
            RetroFactory.getInstance().saveLearn(AppCurrentUser.getInstance().getToken(), requestBody)
                    .subscribeOn(Schedulers.io())
                    .unsubscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Observer<String>() {
                        @Override
                        public void onSubscribe(Disposable d) {
                        }

                        @Override
                        public void onNext(String s) {

                        }

                        @Override
                        public void onError(Throwable e) {

                        }

                        @Override
                        public void onComplete() {

                        }
                    });
        }

    }


    @Override
    protected void onResume() {
        GSYVideoManager.onResume(false);
        super.onResume();
        isPause = false;
    }

    @Override
    protected void onPause() {
        super.onPause();
        GSYVideoManager.onPause();
    }
}
